import React, { useState, useEffect } from 'react';
import { Modal, Form, Input, Button, message } from 'antd';
import { MailOutlined, LockOutlined } from '@ant-design/icons';
import { register, sendVerificationCode } from '@/services/AuthService';
import styles from './index.less';

interface RegisterModalProps {
  visible: boolean;
  onClose: () => void;
  onSuccess: () => void;
  onLogin: () => void;
}

const RegisterModal: React.FC<RegisterModalProps> = ({
  visible,
  onClose,
  onSuccess,
  onLogin,
}) => {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [countdown, setCountdown] = useState(0);

  // 监听 visible 变化，当模态框显示时重置表单
  useEffect(() => {
    if (visible) {
      form.resetFields();
    }
  }, [visible, form]);

  // 处理注册
  const handleSubmit = async (values: any) => {
    try {
      setLoading(true);
      const response = await register({
        email: values.email,
        password: values.password,
        code: values.code,
      });
      
      // 存储用户信息和token
      localStorage.setItem('token', response.token);
      localStorage.setItem('userInfo', JSON.stringify(response));
      
      message.success('注册成功');
      onSuccess();
    } catch (error) {
      message.error('注册失败');
    } finally {
      setLoading(false);
    }
  };

  // 发送验证码
  const handleSendCode = async () => {
    try {
      const email = form.getFieldValue('email');
      if (!email) {
        message.error('请输入邮箱');
        return;
      }
      
      await sendVerificationCode(email, 'REGISTER');
      message.success('验证码已发送');
      
      // 开始倒计时
      setCountdown(60);
      const timer = setInterval(() => {
        setCountdown((prev) => {
          if (prev <= 1) {
            clearInterval(timer);
            return 0;
          }
          return prev - 1;
        });
      }, 1000);
    } catch (error) {
      message.error('发送验证码失败');
    }
  };

  const handleCancel = () => {
    form.resetFields();
    onClose();
  };

  const handleLogin = () => {
    form.resetFields();
    onLogin();
  };

  return (
    <Modal
      title="注册"
      open={visible}
      onCancel={handleCancel}
      footer={null}
      maskClosable={true}
      width={400}
      destroyOnClose
    >
      <Form 
        form={form} 
        onFinish={handleSubmit}
        validateTrigger={['onChange', 'onBlur']}
        requiredMark={true}
      >
        <Form.Item
          name="email"
          rules={[
            { required: true, message: '请输入邮箱' },
            { type: 'email', message: '请输入正确的邮箱格式' },
          ]}
        >
          <Input prefix={<MailOutlined />} placeholder="请输入邮箱" />
        </Form.Item>
        
        <Form.Item
          name="password"
          rules={[
            { required: true, message: '请输入密码' },
            { min: 6, message: '密码长度不能小于6位' },
          ]}
        >
          <Input.Password prefix={<LockOutlined />} placeholder="请输入密码" />
        </Form.Item>
        
        <Form.Item
          name="confirmPassword"
          dependencies={['password']}
          rules={[
            { required: true, message: '请确认密码' },
            ({ getFieldValue }) => ({
              validator(_, value) {
                if (!value || getFieldValue('password') === value) {
                  return Promise.resolve();
                }
                return Promise.reject(new Error('两次输入的密码不一致'));
              },
            }),
          ]}
        >
          <Input.Password prefix={<LockOutlined />} placeholder="请确认密码" />
        </Form.Item>

        <Form.Item
          name="code"
          rules={[{ required: true, message: '请输入验证码' }]}
        >
          <Input
            placeholder="请输入验证码"
            suffix={
              <Button
                type="link"
                disabled={countdown > 0}
                onClick={handleSendCode}
              >
                {countdown > 0 ? `${countdown}秒后重试` : '获取验证码'}
              </Button>
            }
          />
        </Form.Item>

        <Form.Item>
          <Button type="primary" htmlType="submit" block loading={loading}>
            注册
          </Button>
        </Form.Item>
      </Form>
      
      <div className={styles.footer}>
        <Button type="link" onClick={handleLogin}>
          已有账号？立即登录
        </Button>
      </div>
    </Modal>
  );
};

export default RegisterModal; 